package java44th.group.service.wx.cart;

import java44th.group.bean.admin.bo.goods.creategoods.AdminGoodsPO;
import java44th.group.bean.po.*;
import java44th.group.bean.wx.bo.cart.*;
import java44th.group.bean.wx.vo.cart.CartCheckoutVo;
import java44th.group.bean.wx.vo.cart.CartIndexVO;
import java44th.group.bean.wx.vo.cart.CartTotalInfoInnerCartIndexVO;
import java44th.group.bean.wx.vo.cart.CheckedAddressInfoVO;
import java44th.group.mapper.*;
import java44th.group.utils.ReflectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 小焦
 * @since 2022/10/14 10:37
 */

@Service
public class WxCartServiceImpl implements WxCartService {

    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketSystemMapper systemMapper;

    /**
     * 添加购物车接口
     * 尚未开发完成,我先去看视频了
     * 如果该商品已加入购物车,则修改该商品数量,返回该用户所有商品数量,若不存在该商品在cart数据库新增一条记录
     *
     * @param cartAddBO
     * @return java.lang.Integer
     * @author 小焦
     * @since 2022/10/14 上午 10:47
     */
    @Override
    public Integer add(CartAddBO cartAddBO, Integer userId) {
        // {goodsId: 1181087, number: 3, productId: 366}
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andProductIdEqualTo(cartAddBO.getProductId());
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(marketCartExample);
        MarketGoodsProduct goodsProduct = productMapper.selectByPrimaryKey(cartAddBO.getProductId());
        // 判断该商品是否已存在购物车,若已存在
        if (marketCarts.size() > 0) {
            // 则修改购物车中该商品的记录
            for (MarketCart marketCart : marketCarts) {

                Short number = marketCart.getNumber();
                int newNumber = number + cartAddBO.getNumber();
                marketCart.setNumber((short) newNumber);
                marketCart.setPrice(goodsProduct.getPrice());
                marketCart.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                marketCart.setPicUrl(goodsProduct.getUrl());
                cartMapper.updateByExampleSelective(marketCart, marketCartExample);
            }
        } else {
            // 若商品不存在于购物车,则再购物车中新插入一条记录
            AdminGoodsPO goodsPO = goodsMapper.selectByPrimaryKeyToAdminGoodsPO(cartAddBO.getGoodsId());
            int number = cartAddBO.getNumber();
            MarketCart marketCart = new MarketCart();
            // 暂未提供
            marketCart.setUserId(userId);
            marketCart.setGoodsId(cartAddBO.getGoodsId());
            marketCart.setGoodsSn(goodsPO.getGoodsSn());
            marketCart.setGoodsName(goodsPO.getName());
            marketCart.setSpecifications(goodsProduct.getSpecifications());
            marketCart.setProductId(cartAddBO.getProductId());
            marketCart.setPrice(goodsProduct.getPrice());
            marketCart.setPicUrl(goodsProduct.getUrl());
            marketCart.setNumber((short) number);
            marketCart.setAddTime(new Timestamp(System.currentTimeMillis()));
            marketCart.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            marketCart.setDeleted(false);
            marketCart.setChecked(true);
            int count = cartMapper.insertSelective(marketCart);
        }
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andUserIdEqualTo(userId);
        exampleCriteria.andDeletedEqualTo(false);

        List<MarketCart> carts = cartMapper.selectByExample(example);
        int sumNumber = 0;
        for (MarketCart cart : carts) {
            Short number = cart.getNumber();
            sumNumber += number;
        }
        return sumNumber;
    }

    /**
     * 购物车响应界面,返回购物车界面的数据
     *
     * @param userId
     * @return
     * @author 小焦
     * @since 2022/10/14 下午 07:41
     */
    @Override
    public CartIndexVO index(Integer userId) {
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        // 查到用户购物车中商品的list
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        int goodsCount = 0;
        int checkedGoodsCount = 0;
        double goodsAmount = 0;
        double checkedGoodsAmount = 0;
        BigDecimal decimal = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            Short number = marketCart.getNumber();
            double price = marketCart.getPrice().doubleValue();
            goodsAmount += price * number;
            goodsCount += number;
            if (marketCart.getChecked() == true) {
                checkedGoodsAmount += price * number;
                checkedGoodsCount += number;
            }
        }

        CartTotalInfoInnerCartIndexVO cartIndexVO = new CartTotalInfoInnerCartIndexVO();
        cartIndexVO.setGoodsCount(goodsCount);
        cartIndexVO.setGoodsAmount(new BigDecimal(goodsAmount));
        cartIndexVO.setCheckedGoodsCount(checkedGoodsCount);
        cartIndexVO.setCheckedGoodsAmount(new BigDecimal(checkedGoodsAmount));
        CartIndexVO indexVO = new CartIndexVO();
        indexVO.setCartTotal(cartIndexVO);
        indexVO.setCartList(marketCarts);
        return indexVO;
    }

    @Override
    public int fastadd(CartAddBO fastaddBo, Integer userId) {
        int id = 0;
        // {goodsId: 1181087, number: 3, productId: 366}
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andProductIdEqualTo(fastaddBo.getProductId());
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(marketCartExample);
        MarketGoodsProduct goodsProduct = productMapper.selectByPrimaryKey(fastaddBo.getProductId());
        // 判断该商品是否已存在购物车,若已存在
        if (marketCarts.size() > 0) {
            // 则修改购物车中该商品的记录
            for (MarketCart marketCart : marketCarts) {
                // 修改购物车中该商品的记录
                int newNumber = fastaddBo.getNumber();
                marketCart.setNumber((short) newNumber);
                marketCart.setPrice(goodsProduct.getPrice());
                marketCart.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                marketCart.setPicUrl(goodsProduct.getUrl());
                cartMapper.updateByExampleSelective(marketCart, marketCartExample);
                id = marketCart.getId();
            }
        } else {
            // 若商品不存在于购物车,则再购物车中新插入一条记录
            AdminGoodsPO goodsPO = goodsMapper.selectByPrimaryKeyToAdminGoodsPO(fastaddBo.getGoodsId());
            int number = fastaddBo.getNumber();
            MarketCart marketCart = new MarketCart();
            // 暂未提供
            marketCart.setUserId(userId);
            marketCart.setGoodsId(fastaddBo.getGoodsId());
            marketCart.setGoodsSn(goodsPO.getGoodsSn());
            marketCart.setGoodsName(goodsPO.getName());
            marketCart.setSpecifications(goodsProduct.getSpecifications());
            marketCart.setProductId(fastaddBo.getProductId());
            marketCart.setPrice(goodsProduct.getPrice());
            marketCart.setPicUrl(goodsProduct.getUrl());
            marketCart.setNumber((short) number);
            marketCart.setAddTime(new Timestamp(System.currentTimeMillis()));
            marketCart.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            marketCart.setDeleted(false);
            cartMapper.insertSelective(marketCart);
            id = marketCart.getId();
        }
        // 返回购物车中该购物记录的id
        return id;
    }

    @Override
    public int insert(List<MarketCart> insertmsg) {
        for (MarketCart marketCart : insertmsg) {
            int i = cartMapper.insertSelective(marketCart);
        }

        return 0;
    }

    @Override
    public CartIndexVO checked(CartCheckedBo checkedBo, Integer userId) {
        MarketCart marketCart = new MarketCart();
        boolean checked = true;
        if (checkedBo.getIsChecked() == 1) {
            checked = true;
        } else {
            checked = false;
        }

        marketCart.setChecked(checked);

        for (Integer productId : checkedBo.getProductIds()) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andProductIdEqualTo(productId);
            int count = cartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }


        CartIndexVO indexVO = index(userId);
        return indexVO;
    }

    @Override
    public int update(CartUpdateBo updateBo) {
        MarketCart marketCart = new MarketCart();
        marketCart.setNumber(updateBo.getNumber());
        marketCart.setId(updateBo.getId());
        int count = 0;
        try {
            count = cartMapper.updateByPrimaryKeySelective(marketCart);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return count;
    }

    @Override
    public CartIndexVO delete(ProductIdsBO productIds, Integer userId) {
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        for (Integer productId : productIds.getProductIds()) {
            MarketCartExample example = new MarketCartExample();
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andProductIdEqualTo(productId);
            criteria.andUserIdEqualTo(userId);
            cartMapper.updateByExampleSelective(marketCart, example);
        }
        CartIndexVO index = index(userId);
        return index;
    }

    /**
     * 1. 获取请求参数--cartId=0&addressId=0&couponId=-1&userCouponId=-1&grouponRulesId=0
     * 2. 处理业务逻辑--下单页面回显
     * 3. 返回响应--
     *
     * @param checkoutBo
     * @param userId
     * @return java44th.group.bean.wx.vo.cart.CartCheckoutVo
     * @author 小焦
     * @since 2022/10/15 下午 02:54
     */
    @Override
    public CartCheckoutVo checkout(CartCheckoutBo checkoutBo, Integer userId) {
        List<MarketCart> marketCarts = new ArrayList<>();
        MarketCart theMarketCart= new MarketCart();
        if(checkoutBo.getCartId()<=0){
            MarketGrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(checkoutBo.getGrouponRulesId());
            MarketCartExample example = new MarketCartExample();
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andDeletedEqualTo(false);
            criteria.andCheckedEqualTo(true);
             marketCarts = cartMapper.selectByExample(example);
        }else {
             theMarketCart = cartMapper.selectByPrimaryKey(checkoutBo.getCartId());
            marketCarts.add(theMarketCart);
        }


        // 获取该用户的地址信息
        MarketAddress address = null;
        CheckedAddressInfoVO addressInfoVO = null;
        if (checkoutBo.getAddressId() != 0) {
            address = addressMapper.selectByPrimaryKey(checkoutBo.getAddressId());
            addressInfoVO = ReflectUtils.copyObject(address, CheckedAddressInfoVO.class);
        } else {
            // 有多个地址的处理情况
            MarketAddressExample addressExample = new MarketAddressExample();
            MarketAddressExample.Criteria addressExampleCriteria = addressExample.createCriteria();
            addressExampleCriteria.andUserIdEqualTo(userId);
            List<MarketAddress> marketAddresses = addressMapper.selectByExample(addressExample);
            if (marketAddresses.size() > 0) {
                for (MarketAddress marketAddress : marketAddresses) {
                    // 如果有默认地址,则给默认地址
                    if (marketAddress.getIsDefault() == true) {
                        addressInfoVO = ReflectUtils.copyObject(marketAddress, CheckedAddressInfoVO.class);
                        break;
                    }
                }
                if(addressInfoVO==null){
                    addressInfoVO = ReflectUtils.copyObject(marketAddresses.get(0), CheckedAddressInfoVO.class);
                }
            }
        }
        CartCheckoutVo checkoutVo = new CartCheckoutVo();
        MarketCoupon marketCoupon;
        BigDecimal discount = new BigDecimal(0);
//        if (checkoutBo.getCouponId() == 0) {
//            checkoutVo.setCouponPrice(discount);
//        } else {
////            marketCoupon = couponMapper.selectByPrimaryKey(checkoutBo.getCouponId());
//            // 优惠金额
//
//            discount = getMarketCoupon(checkoutBo.getCouponId());
////                    marketCoupon.getDiscount();
//            // CouponPrice
//            checkoutVo.setCouponPrice(discount);
//        }


        // 商品合计
        double sumMoney = 0;
        for (MarketCart marketCart : marketCarts) {
            sumMoney += marketCart.getPrice().doubleValue() * marketCart.getNumber();
        }

        double couponPrice=0;
        // 可用优惠券合计


        couponPrice = setCheckOutVoCouponRelated(checkoutVo, userId);




//        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
//        MarketCouponUserExample.Criteria userExample = couponUserExample.createCriteria();
//        userExample.andUserIdEqualTo(userId);
//        userExample.andStatusEqualTo((short) 0);
//        userExample.andDeletedEqualTo(false);
//        long couponLength = couponUserMapper.countByExample(couponUserExample);

        // 获取运费
        MarketSystem marketSystem = systemMapper.selectByPrimaryKey(6);
        int expressFreightMin = Integer.parseInt(marketSystem.getKeyValue());
        MarketSystem marketSystem1 = systemMapper.selectByPrimaryKey(8);

        // GrouponRulesId
        checkoutVo.setGrouponRulesId(checkoutBo.getGrouponRulesId());
        //FreightPrice
        int expressFreightValue = 0;

        // 运费
        if (sumMoney - discount.doubleValue() < expressFreightMin) {
            expressFreightValue = Integer.parseInt(marketSystem1.getKeyValue());
            checkoutVo.setFreightPrice(new BigDecimal(expressFreightValue));
        } else {
            checkoutVo.setFreightPrice(new BigDecimal(expressFreightValue));
        }
        // ActualPrice
        checkoutVo.setActualPrice(new BigDecimal(sumMoney + expressFreightValue - couponPrice));
        // OrderTotalPrice
        checkoutVo.setOrderTotalPrice(new BigDecimal(sumMoney + expressFreightValue));
        // cartId
        if (marketCarts.size() == 1) {
            for (MarketCart marketCart : marketCarts) {
                checkoutVo.setCartId(marketCart.getId());
            }
        } else {
            checkoutVo.setCartId(checkoutBo.getCartId());
        }
        // UserCouponId
        checkoutVo.setUserCouponId(checkoutBo.getUserCouponId());
        // CouponId
        checkoutVo.setCouponId(checkoutBo.getCouponId());
        // GoodsTotalPrice
        checkoutVo.setGoodsTotalPrice(new BigDecimal(sumMoney));
        // AddressId
        checkoutVo.setAddressId(checkoutBo.getAddressId());
        // GrouponPrice
        checkoutVo.setGrouponPrice(new BigDecimal(0));

        // AvailableCouponLength
//        checkoutVo.setAvailableCouponLength(couponLength);
        checkoutVo.setCheckedAddress(addressInfoVO);
        checkoutVo.setCheckedGoodsList(marketCarts);
        return checkoutVo;
    }

    /**
     * author: 帅浩浩
     * 查询所有优惠券 默认选择第一个返回给用户 并返回该优惠券的价值
     *  @param checkoutVo 返回给前端的值
     * @param
     * @param userId     用户id
     */
    private double setCheckOutVoCouponRelated(CartCheckoutVo checkoutVo, Integer userId) {

        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria userExample = couponUserExample.createCriteria();
        userExample.andUserIdEqualTo(userId);
        userExample.andStatusEqualTo((short) 0);
        userExample.andDeletedEqualTo(false);
        List<MarketCouponUser> couponLength = couponUserMapper.selectByExample(couponUserExample);
        int maxCouponUserId = -1;
        int maxCouponId = -1;
        BigDecimal maxCouponPrice = null;

        double couponPrice = 0;
        if (couponLength.size() > 0) {
            maxCouponUserId = couponLength.get(0).getUserId();
            maxCouponId = couponLength.get(0).getCouponId();
            MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(maxCouponId);
            maxCouponPrice = marketCoupon.getDiscount();
        }

        checkoutVo.setCouponId(maxCouponId);
        checkoutVo.setUserCouponId(maxCouponUserId);
        checkoutVo.setCouponPrice(maxCouponPrice);
        checkoutVo.setAvailableCouponLength(couponLength.size());

//        for (MarketCouponUser marketCouponUser : couponLength) {
//            if (maxCouponPrice<marketCouponUser.get)
//        }
        if (maxCouponPrice != null) {
            couponPrice = maxCouponPrice.doubleValue();
        }
        return couponPrice;
    }


    @Override
    public long goodscount(Integer userId) {
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        long count = cartMapper.countByExample(example);
        return count;
    }

}
